package com.cn.kehong.service;


import com.cn.kehong.api.IPlanMothDetailService;
import com.cn.kehong.api.IPlanMothService;
import com.cn.kehong.api.IPlanYearService;
import com.cn.kehong.api.ISysItemService;
import com.cn.kehong.dao.PlanMothMapper;
import com.cn.kehong.dao.ProductPeiTouMapper;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@EnableScheduling
@Service
public class PlanMothServiceImpl implements IPlanMothService {

    @Autowired
    private PlanMothMapper planMothMapper;

    @Autowired
    private IPlanMothDetailService planMothDetailService;

    @Autowired
    private IPlanYearService planYearService;

    @Autowired
    private ProductPeiTouMapper productPeiTouMapper;

    @Autowired
    private ISysItemService sysItemService;

    @Override
    public List<PlanMoth> getPlanMothList(QueryForm queryForm) throws Exception {
        int count = planMothMapper.selectPlanMothListCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        if (StringUtils.isNotEmpty(queryForm.getFactoryName())){
            String[] split = queryForm.getFactoryName().split("-");
            queryForm.setFactoryName(split[0]);
        }
        List<PlanMoth> planMoths = planMothMapper.selectPlanMothList(queryForm);
        if (planMoths.size()>0){
            planMoths.get(0).setCount(count);
        }
        return planMoths;
    }

    @Override
    public List<PlanMothVo> getCurrentYearPlanMothList() throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String year = simpleDateFormat.format(new Date());
        List<PlanMoth> planMoths = planMothMapper.selectTodayYearPlanMothDatas(year + "-");
        if (CollectionUtils.isEmpty(planMoths)) {
            return Lists.newArrayList();
        }
        if (planMoths.size() > 12) {
            throw new Exception("查询月计划超过12条数据！");
        }
        //状态
        Map<String, String> statusMap = Maps.newLinkedHashMap();
        //成品合计
        Map<String, String> yearMap = Maps.newHashMap();
        //计划合计
        Map<String, String> hejiMap = Maps.newHashMap();
        //偏差
        Map<String, String> pianChaMap = Maps.newHashMap();
        //偏差率
        Map<String, String> pianChaMapPercent = Maps.newHashMap();
        for (int i = 1; i <= 12; i++) {
            yearMap.put(i + "", "0");
            pianChaMap.put(i + "", "0");
            hejiMap.put(i + "", "0");
            pianChaMapPercent.put(i + "", "0");
            statusMap.put(i + "", "待编制");
        }
        List<PlanMothVo> planMothVos = new LinkedList<>();
        Map<String, Map<String, Double>> tempMap = Maps.newLinkedHashMap();

        List<SysItem> sysItems = sysItemService.getMgItemByType("10");
        for(SysItem sys:sysItems){
            this.initPlanMothMap(tempMap, sys.getItemName());
        }
        for (PlanMoth planMoth : planMoths) {
            String mothYear = planMoth.getYearMoth();
            int moth = Integer.parseInt(mothYear.split("-")[1]);
            statusMap.put(moth + "", planMoth.getPlanStatusCn());
            List<PlanMothDetail> details = planMoth.getPlanMothDetails();
            if (StringUtils.isNotEmpty(planMoth.getMothTotal())) {
                double hj1 = Double.parseDouble(hejiMap.get(moth + ""));
                hejiMap.put(moth + "", (hj1 + Double.parseDouble(planMoth.getMothTotal())) + "");
            }
            for (PlanMothDetail detail : details) {
                String grade = detail.getGradeValue();
                double total = this.getPlanMothValue(detail);
                if (!tempMap.containsKey(grade)) {
                    continue;
                }
                Map<String, Double> gradeMap = tempMap.get(grade);
                double value = gradeMap.get(moth + "");
                total += value;
                gradeMap.put(moth + "", total);
            }
        }

        for (String key : tempMap.keySet()) {
            PlanMothVo vo = new PlanMothVo();
            vo.setName(key);
            Map<String, Double> gradeMap = tempMap.get(key);
            for (String key2 : gradeMap.keySet()) {
                Class<PlanMothVo> cls = PlanMothVo.class;
                Method method = cls.getMethod("setV" + key2, String.class);
                method.invoke(vo, gradeMap.get(key2) + "");
            }
            planMothVos.add(vo);
        }

        PlanYear planYear = planYearService.getYearPlanByYear(year);
        List<PlanYearDetail> yearDetails = planYear.getPlanYearDetails();
        if (CollectionUtils.isNotEmpty(yearDetails)) {
            for (PlanYearDetail yearDetail : yearDetails) {
                String itemType = yearDetail.getItemType();
                if (itemType.indexOf("计划产出") < 0) {
                    continue;
                }
                for (int i = 1; i <= 12; i++) {
                    Double v = Double.parseDouble(yearMap.get(i + ""));
                    Class<?> clazz = PlanYearDetail.class;
                    Field[] fields = clazz.getDeclaredFields();
                    for (Field field : fields) {
                        field.setAccessible(true); // 设置可访问私有属性
                        if (StringUtils.equals(field.getName(), "v" + i)) {
                            Object value = field.get(yearDetail);
                            if (null != value && StringUtils.isNotEmpty(value.toString())) {
                                v += Double.parseDouble(value.toString());
                                yearMap.put(i + "", v + "");
                            }
                        }
                    }
                }
            }
        }
        for (int i = 1; i <= 12; i++) {
            String cps = yearMap.get(i + "");
            String heji = hejiMap.get(i + "");
            double dist = Double.parseDouble(heji) - Double.parseDouble(cps);
            if (dist > 0) {
                dist = 0;
            }
            pianChaMap.put(i + "", dist + "");
            if (Double.parseDouble(cps) > 0) {
                double percent = (dist / Double.parseDouble(cps)) * 100.0;
                String per = NumberUtil.getPoint(percent, 2);
                pianChaMapPercent.put(i + "", per);
            }
        }
        PlanMothVo hejiVo = this.setPlanMothVo("计划合计", hejiMap);
        PlanMothVo statusVo = this.setPlanMothVo("计划状态", statusMap);
        PlanMothVo yearVo = this.setPlanMothVo("成品合计", yearMap);
        PlanMothVo pianchaVo = this.setPlanMothVo("偏差数量", pianChaMap);
        PlanMothVo pianchaPerVo = this.setPlanMothVo("偏差率%", pianChaMapPercent);
        planMothVos.add(hejiVo);
        planMothVos.add(statusVo);
        planMothVos.add(yearVo);
        planMothVos.add(pianchaVo);
        planMothVos.add(pianchaPerVo);
        return planMothVos;
    }

    @Override
    public List<PlanMoth> getAllYearPlanMothList(QueryForm queryForm) throws Exception {
        List<PlanMoth> planMoths = planMothMapper.selectAllYearPlanMothDatas(queryForm);
        return planMoths;
    }

    private PlanMothVo setPlanMothVo(String name, Map<String, String> values) throws Exception {
        PlanMothVo planMothVo = new PlanMothVo();
        planMothVo.setName(name);
        for (int i = 1; i <= 12; i++) {
            Class<PlanMothVo> cls = PlanMothVo.class;
            Method method = cls.getMethod("setV" + i, String.class);
            method.invoke(planMothVo, values.get(i + ""));
        }
        return planMothVo;
    }

    private void initPlanMothMap(Map<String, Map<String, Double>> tempMap, String key) {
        Map<String, Double> map = Maps.newLinkedHashMap();
        for (int i = 1; i <= 12; i++) {
            map.put(i + "", 0.0);
        }
        tempMap.put(key, map);
    }

    @Override
    public PlanMoth getCurrentPlanMoth() throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String moth = simpleDateFormat.format(new Date());
        PlanMothExample example = new PlanMothExample();
        example.createCriteria().andYearMothEqualTo(moth).andStatusEqualTo(Constants.NORMAL_STATUS);
        example.setOrderByClause("current_version desc");
        List<PlanMoth> planMoths = planMothMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(planMoths)) {
            return new PlanMoth();
        }
        PlanMoth planMoth = planMoths.get(0);
        String id = planMoth.getId();
        List<PlanMothDetail> planMothDetails = planMothDetailService.getPlanMothDetails(id);
        planMoth.setPlanMothDetails(planMothDetails);
        return planMoth;
    }

    @Override
    public String addPlanMoth(PlanMoth planMoth) throws Exception {
        String id = CommonUtil.generateRandomNum("planMoth-");
        String yearMoth = planMoth.getYearMoth();
        if (StringUtils.isEmpty(yearMoth)) {
            return "年月不能为空！";
        }
        planMoth.setId(id);
        PlanMothExample example = new PlanMothExample();
        example.createCriteria().andYearMothEqualTo(yearMoth).andStatusEqualTo(Constants.NORMAL_STATUS);
        int existCount = planMothMapper.countByExample(example);
        if (existCount > 0) {
            return "月度报告已经存在，无法新增，只能修订！";
        }
        List<PlanMothDetail> planMothDetails = planMoth.getPlanMothDetails();
        if (CollectionUtils.isEmpty(planMothDetails)) {
            return "数据异常！";
        }
        double total = 0.0;
        for (PlanMothDetail detail : planMothDetails) {
            detail.setPlanMothId(id);
            detail.setMothYear(planMoth.getYearMoth());
            total += this.getPlanMothValue(detail);
        }
        planMoth.setMothTotal(total + "");
        int count = planMothMapper.insertSelective(planMoth);
        if (count < 1) {
            return "插入月度表异常！";
        }
        String resp = planMothDetailService.addPlanMothDetail(planMothDetails);
        if (StringUtils.isNotEmpty(resp)) {
            throw new Exception(resp);
        }
        return resp;
    }

    private double getPlanMothValue(PlanMothDetail detail) throws Exception {
        double total = 0.0;
        Class<?> clazz = PlanMothDetail.class;
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true); // 设置可访问私有属性
            if (field.getName().indexOf("v") == 0) {
                Object value = field.get(detail); // 获取属性值
                if (null != value && StringUtils.isNotEmpty(value.toString())) {
                    total += Double.parseDouble(value.toString());
                }
            }
        }
        return total;
    }

    @Override
    public String updatePlanMothVersion(PlanMoth planMoth) throws Exception {
        String id = planMoth.getId();
        if (StringUtils.isEmpty(id)) {
            return "主键为空！";
        }
        PlanMoth exist = planMothMapper.selectPlanMothById(id);
        if (null == exist) {
            return "未查询到月度计划！";
        }
        String planStatus = exist.getPlanStatus();

        if (StringUtils.equals(planStatus, "0") || StringUtils.equals(planStatus, "5")) {
            return "月度计划在待执行状态,无需变更";
        }

        List<PlanMothDetail> planMothDetails = planMoth.getPlanMothDetails();
        if (CollectionUtils.isEmpty(planMothDetails)) {
            return "数据异常！";
        }

        String currentVersion = exist.getCurrentVersion();
        String nextVersion = (Integer.parseInt(currentVersion) + 1) + "";

        PlanMothExample example1 = new PlanMothExample();
        example1.createCriteria().andCurrentVersionEqualTo(nextVersion).andYearMothEqualTo(planMoth.getYearMoth()).andStatusEqualTo(Constants.NORMAL_STATUS);
        int count = planMothMapper.countByExample(example1);
        if (count > 0) {
            return "版本v" + nextVersion + "已经存在";
        }
        String existYear = exist.getYearMoth();
        PlanMothExample example = new PlanMothExample();
        example.createCriteria().andYearMothEqualTo(existYear);
        PlanMoth update = new PlanMoth();
        update.setLatestVersion("0");
        count = planMothMapper.updateByExampleSelective(update, example);
        if (count < 0) {
            return "更新旧版本异常！";
        }

        planMoth.setPid(id);
        String newId = CommonUtil.generateRandomNum("planMoth-");
        planMoth.setId(newId);
        planMoth.setCurrentVersion(nextVersion);
        for (PlanMothDetail detail : planMothDetails) {
            detail.setPlanMothId(newId);
        }
        count = planMothMapper.insertSelective(planMoth);
        if (count < 1) {
            throw new Exception("插入月度表异常！");
        }
        String resp = planMothDetailService.addPlanMothDetail(planMothDetails);
        if (StringUtils.isNotEmpty(resp)) {
            throw new Exception(resp);
        }
        return resp;
    }

    @Override
    public String updatePlanMoth(PlanMoth planMoth) throws Exception {
        String id = planMoth.getId();
        if (StringUtils.isEmpty(id)) {
            return "主键为空！";
        }
        PlanMoth exist = planMothMapper.selectPlanMothById(id);
        if (null == exist) {
            return "未查询到月度计划！";
        }
        String planStatus = exist.getPlanStatus();
        if (!StringUtils.equals(planStatus, "0") && !StringUtils.equals(planStatus, "5")) {
            return "月度计划不在待执行状态，无法编辑";
        }

        List<PlanMothDetail> planMothDetails = planMoth.getPlanMothDetails();
        if (CollectionUtils.isEmpty(planMothDetails)) {
            return "数据异常！";
        }

        PlanMothExample example = new PlanMothExample();
        example.createCriteria().andIdEqualTo(id);

        int count = planMothMapper.updateByExampleSelective(planMoth, example);
        if (count < 1) {
            return "更新异常!";
        }
        String resp = planMothDetailService.updatePlanMothDetail(planMothDetails);
        if (StringUtils.isNotEmpty(resp)) {
            throw new Exception(resp);
        }
        return resp;
    }

    @Override
    public String updateCheckPlanMoth(PlanMoth planMoth) throws Exception {
        if (StringUtils.isEmpty(planMoth.getId())) {
            return "缺少主键！";
        }

        PlanMoth exist = planMothMapper.selectPlanMothById(planMoth.getId());
        if (null == exist) {
            return "未查询到月度计划！";
        }
        if (!StringUtils.equals(exist.getPlanStatus(), "1")) {
            return "年度计划不在待审核状态";
        }
        if (StringUtils.equals(planMoth.getPlanStatus(), "2")) {
            String year = exist.getYearMoth();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            String actualYear = simpleDateFormat.format(new Date());
            if (actualYear.compareTo(year) < 0) {
                planMoth.setPlanStatus("3");
            }
        }

        PlanMothExample example = new PlanMothExample();
        example.createCriteria().andIdEqualTo(planMoth.getId());
        int count = planMothMapper.updateByExampleSelective(planMoth, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String deletePlanMothById(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            return "缺少主键！";
        }
        PlanMoth exist = planMothMapper.selectPlanMothById(id);
        if (null == exist) {
            return "未查询到月度计划！";
        }
        if (!StringUtils.equals(exist.getPlanStatus(), "0")) {
            return "月度计划不在待执行状态，无法删除";
        }
        PlanMoth update = new PlanMoth();
        update.setStatus(Constants.DEL_STATUS);

        PlanMothExample example = new PlanMothExample();
        example.createCriteria().andIdEqualTo(id);

        int count = planMothMapper.updateByExampleSelective(update, example);
        if(count < 1){
            return "删除数据异常！";
        }
        PlanMoth latestVersion = planMothMapper.selectLatestPlanMothByMoth(exist.getYearMoth());
        if(null !=latestVersion){
            PlanMoth update1 = new PlanMoth();
            update1.setLatestVersion("1");
            PlanMothExample example1 = new PlanMothExample();
            example1.createCriteria().andIdEqualTo(latestVersion.getId());
            count =  planMothMapper.updateByExampleSelective(update1, example1);
            if(count < 1){
                throw new Exception("更新表异常!");
            }
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public int getCheckPlanMothCount() throws Exception {
        PlanMothExample example = new PlanMothExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andPlanStatusEqualTo("1");
        int count = planMothMapper.countByExample(example);
        return count;
    }

    @Override
    public String getPlanMothDayValue(QueryForm queryForm) throws Exception {
        String mothYearDay = queryForm.getYearMoth();
        String factoryName = queryForm.getFactoryName();
        if (StringUtils.isEmpty(mothYearDay) || StringUtils.isEmpty(factoryName) ) {
            return "";
        }
        String factory = factoryName.split("-")[0];
        String[] splits = mothYearDay.split("-");
        String mothYear = splits[0] + "-" + splits[1];
        int day = Integer.parseInt(splits[2]);
        PlanMothExample example = new PlanMothExample();
        example.createCriteria().andFactoryNameEqualTo(factory).andYearMothEqualTo(mothYear).andStatusEqualTo(Constants.NORMAL_STATUS).andLatestVersionEqualTo("1");
        List<PlanMoth> planMoths = planMothMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(planMoths) || planMoths.size() != 1) {
            return "";
        }
        String id = planMoths.get(0).getId();
        List<PlanMothDetail> planMothDetails = planMothDetailService.getPlanMothDetails(id);
        if (CollectionUtils.isEmpty(planMothDetails)) {
            return "";
        }
        double total = 0.0;
        for (PlanMothDetail detail : planMothDetails) {
            if (StringUtils.equals(detail.getFactory(), factoryName)) {
                String key = "v" + day;
                Class<?> clazz = PlanMothDetail.class;
                Field field = clazz.getDeclaredField(key);
                field.setAccessible(true);
                Object value = field.get(detail);
                if (null != value &&StringUtils.isNotEmpty(value.toString())) {
                    double v = Double.parseDouble(value.toString());
                    total += v;
                }
            }
        }
        return total+"";
    }

    @Override
    public String isHavingMoth(String month) throws Exception {
        PlanMothExample example = new PlanMothExample();
        example.createCriteria().andYearMothEqualTo(month).andStatusEqualTo(Constants.NORMAL_STATUS);
        int existCount = planMothMapper.countByExample(example);
        if (existCount > 0) {
            return "月度报告已经存在，无法新增，只能修订！";
        }
        return null;
    }

    @Override
    public List<PlanMoth> getPlanMothDayPlans() throws Exception {
        QueryForm queryForm = new QueryForm();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String actualYearMoth = simpleDateFormat.format(new Date());
        queryForm.setLatestVersion("1");
        queryForm.setYearMoth(actualYearMoth);
        List<PlanMoth> planMoths = planMothMapper.selectAllYearPlanMothDatas(queryForm);
        if(CollectionsUtil.isEmpty(planMoths)){
          return  Lists.newArrayList();
        }
        PlanMoth planMoth= planMoths.get(0);
        List<PlanMothDetail> planMothDetails = planMoth.getPlanMothDetails();

        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectCurrentMothProductPeiTou(actualYearMoth+"-");
        for(ProductPeiTou productPeiTou : productPeiTous){

        }
        return null;
    }


    //    @Scheduled(cron = "*/5 * * * * ?")
    @Scheduled(cron = "0 0 */2 * * ?")
    public void updateScheduler() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String actualYearMoth = simpleDateFormat.format(new Date());
        PlanMothExample example = new PlanMothExample();
        List<String> statusList = Lists.newArrayList("2", "3");
        example.createCriteria().andPlanStatusIn(statusList).andStatusEqualTo(Constants.NORMAL_STATUS);

        List<PlanMoth> planMoths = planMothMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(planMoths)) {
            List<PlanMoth> updates = Lists.newArrayList();
            for(PlanMoth plan:planMoths){
                String yearMoth = plan.getYearMoth();
                String planStatus = plan.getPlanStatus();
                if(!StringUtils.equals(yearMoth,actualYearMoth)&&StringUtils.equals(planStatus,"2")){
                    PlanMoth update = new PlanMoth();
                    update.setPlanStatus("4");
                    update.setId(plan.getId());
                    updates.add(update);
                }else if(StringUtils.equals(yearMoth,actualYearMoth)&&StringUtils.equals(planStatus,"3")){
                    PlanMoth update = new PlanMoth();
                    update.setPlanStatus("2");
                    update.setId(plan.getId());
                    updates.add(update);
                }
            }
            if(CollectionsUtil.isNotEmpty(updates)){
                planMothMapper.batchUpdatePlanMoths(updates);
            }
        }
    }
}
